# -*- encoding: utf-8 -*-
import urllib,urllib2
import requests
import json
import os
def convert(x,y,s_srs,t_srs):
    url='http://epsg.io/trans'
    textmod ={'x':x,'y':y,'s_srs':s_srs,'t_srs':t_srs}
    textmod = urllib.urlencode(textmod)
    print(textmod)
    #输出内容:password=admin&user=admin
    req = urllib2.Request(url = '%s%s%s' % (url,'?',textmod))
    print(req.get_full_url())
    res = urllib2.urlopen(req)
    res = res.read()
    print(res)
def request(data,s_srs,t_srs):
    url='http://epsg.io/trans'
    textmod ={'data':data,'s_srs':s_srs,'t_srs':t_srs}
    response = requests.get(url, params=textmod)
    jsonData = response.json()
    coor=json.dumps(jsonData)
    return coor
    # print(json)
# 遍历指定目录，显示目录下的所有文件名
def eachFile(filepath):
    pathDir =  os.listdir(filepath)
    for allDir in pathDir:
        child = os.path.join('%s%s' % (filepath, allDir))
        childPath=child.decode('gbk') # .decode('gbk')是解决中文显示乱码问题
        with open(childPath, 'r') as file:
            json_data = file.read()
            json_data = json.loads(json_data)
            s_srs=json_data['s_srs']
            t_srs=json_data['t_srs']
            cdata=json_data['data']
            coor=request(cdata,s_srs,t_srs)
            outPutPath=os.path.splitext(childPath)[0]+'Convert.txt'
            with open(outPutPath, 'w') as wfile:
                geojson=json.dumps(coor)
                geojson.replace('u\'','\'')
                geojson=geojson.decode("unicode-escape") 
                wfile.write(geojson)
                print('success')
def readFile():
    path=os.path.dirname(os.path.realpath(__file__))#获取py文件所在文件夹
    txtDirPath=path+'\\txt\\'
    eachFile(txtDirPath)
def reptile():
    url='http://epsg.io/trans?y=2544675&x=36518161&t_srs=4326&s_srs=2360'
    page = urllib.urlopen(url)
    return page.read()
if __name__=='__main__':
    # request(36518161,2544675,2360,4326)
    readFile()